package org.example.controller;

import org.example.bean.User;
import org.example.service.Impl.UserServise;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    UserServise userServise;
    @RequestMapping("/query1.do")
    @ResponseBody   //1、修饰当前方法返回类型为JSON
    public List<User> getAll(){  //2、将需要转换成json格式的对象直接返回
        List<User> list =  userServise.getAll();
        System.out.println("打印USER表");
        return list;
    }
    @RequestMapping("/delete.do")
    public void delete(int id){
        userServise.del(id);
    }
    @RequestMapping("/test.do")
    public String add(@RequestParam("username") String username, @RequestParam("password") String password,@RequestParam("rname") String rname,@RequestParam("name") String name
            ,@RequestParam("state") String state,@RequestParam("type") String type,@RequestParam("tel") long tel,@RequestParam("sname") String sname,@RequestParam("text") String text){
        User user = new User();
        user.setUname(username);
        user.setName(name);
        user.setTel(tel);
        user.setSname(sname);
        user.setState(state);
        user.setType(type);
        user.setRname(rname);
        user.setText(text);
        user.setPassword(password);
        userServise.add(user);
        return "用户管理";
    }
    @RequestMapping("/update1.do")
    public String update(@RequestParam("uname") String uname, @RequestParam("id") int id,@RequestParam("rname") String rname,@RequestParam("name") String name
            ,@RequestParam("state") String state,@RequestParam("type") String type,@RequestParam("tel") long tel,@RequestParam("sname") String sname,@RequestParam("text") String text){
        User user = new User();
        user.setId(id);
        user.setUname(uname);
        user.setName(name);
        user.setTel(tel);
        user.setSname(sname);
        user.setState(state);
        user.setType(type);
        user.setRname(rname);
        user.setText(text);
        userServise.update(user);
        return "用户管理";
    }
    @RequestMapping(value = "/login.do")
    public String login(@RequestParam("uname") String uname, @RequestParam("password") String password, Model model) {
        User user = userServise.getUserByUsername(uname);
        if (user != null && user.getPassword().equals(password)) {
            return "index.html"; // 登录成功，跳转到欢迎页面
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "登录"; // 登录失败，返回登录页面并显示错误信息
        }
    }
}
